package com.app.system.permission.web;

import com.app.log.annotation.MyLog;
import com.app.system.common.EncipherPwd;
import com.app.system.config.requestLimit.RequestLimit;
import com.app.system.config.shiro.MyShiroRealm;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.model.SysPermission;
import com.app.system.permission.model.SysRole;
import com.app.system.permission.model.UserInfo;
import com.app.system.permission.service.DataDictService;
import com.app.system.permission.service.SysPermissionService;
import com.app.system.permission.service.UserInfoService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.base64.Base64Utils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by wcf-pc on 2018/4/4.
 */
@Controller
@RequestMapping(value = "/main/*")
@SuppressWarnings("all")
public class MainController {

    private static final Logger log = LoggerFactory.getLogger(MainController.class);

    @Resource
    private SysPermissionService sysPermissionService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private DataDictService dataDictService;
    @Resource
    private EncipherPwd encipherPwd;
    @Resource
    private MyShiroRealm myShiroRealm;

    /**
     * 主窗体
     *
     * @param model
     */
    @RequestLimit
    @RequestMapping(value = {"/", "/main/control"})
    public void control(ModelMap model) {
    }

    @ResponseBody
    @RequestMapping("/main/getSysRoleInfo")
    public Map getSysRoleInfo() {
        Set<SysRole> sysRoleSet = WebUtils.getLoginUserInfo().getRoleList();
        SysRole sysRole = sysRoleSet.iterator().next();
        Iterator<SysRole> item = sysRoleSet.iterator();
        List<String> roleList = null;
        Map<String, List<String>> mapList = Maps.newHashMap();
        while (item.hasNext()) {
            roleList = null;
            SysRole role = item.next();
            if (role.getAvailable()) {
                String phoneOrPc = role.getPhoneOrPc();
                roleList = mapList.get(phoneOrPc);
                roleList = CollectionUtils.isEmpty(roleList) ? Lists.newArrayList() : roleList;
                roleList.add(role.getToUrl());
                mapList.put(phoneOrPc, roleList);
            }
        }
        return mapList;
    }

    @RequestLimit
    @RequestMapping(value = {"/main/main"})
    public void main(ModelMap model) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        UserInfo userInfo = this.userInfoService.findByUsername(username);
        model.addAttribute("userInfo", userInfo);

        List<SysPermission> sysPermissionList = this.sysPermissionService.findListByUsername(username);
        model.addAttribute("sysPermissionList", sysPermissionList);

        Map<String, DataDict> dataDictMap = dataDictService.getMapByParentNameForName("系统配置");
        model.addAttribute("dataDictMap", dataDictMap);
    }

    @RequestMapping({"/main/console"})
    public void console() {

    }

    /**
     * 用户基本信息
     *
     * @param request
     * @param model
     */
    @RequestMapping({"/main/baseInfo"})
    public void baseInfo(HttpServletRequest request, ModelMap model) {
        Object obj = SecurityUtils.getSubject().getPrincipal();
        Precondition.checkSqdsArguement(obj != null && !"".equals(obj.toString()), "未登录用户");

        String username = String.valueOf(obj);
        UserInfo userInfo = this.userInfoService.findByUsername(username);
        model.addAttribute("userInfo", userInfo);
    }

    @MyLog(value = "main基本信息保存")
    @RequestMapping({"/main/saveBaseInfo"})
    @ResponseBody
    public Response saveBaseInfo(HttpServletRequest request) {
        Object obj = SecurityUtils.getSubject().getPrincipal();
        Precondition.checkSqdsArguement(obj != null && !"".equals(obj.toString()), "未登录用户");

        String username = String.valueOf(obj);
        UserInfo userInfo = this.userInfoService.findByUsername(username);
        Precondition.checkSqdsArguement(userInfo != null, "无效用户");

        ServletRequestDataBinder binder = new ServletRequestDataBinder(userInfo);
        binder.bind(request);
        this.userInfoService.save(userInfo);

        return new Response("0001", "保存成功");
    }

    /**
     * 密码修改
     *
     * @param request
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @MyLog(value = "main密码修改")
    @RequestMapping({"/main/savePwd"})
    @ResponseBody
    public Response savePwd(HttpServletRequest request, String oldPwd, String newPwd) {
        Object obj = SecurityUtils.getSubject().getPrincipal();
        Precondition.checkSqdsArguement(obj != null && !"".equals(obj.toString()), "未登录用户");

        String username = String.valueOf(obj);
        UserInfo userInfo = this.userInfoService.findByUsername(username);
        Precondition.checkSqdsArguement(userInfo != null, "无效用户");
        Map<String, String> map = null;
        String encipherPassword = null, encipherSalt = null;
        //比对原始密码正确性
        encipherPassword = encipherPwd.getCredentialsPwd(username, oldPwd, userInfo.getSalt());

        Precondition.checkAjaxArguement(encipherPassword.equals(userInfo.getPassword()), "9999", "原始密码输入有误");

        //产生新的秘钥
        map = encipherPwd.getEncipherPwd(username, newPwd);
        encipherPassword = map.get("password");
        encipherSalt = map.get("salt");
        this.userInfoService.updatePwd(userInfo.getId(), encipherPassword, encipherSalt);//更新密码

        return new Response("0001", "密码已修改，请退出系统重新登录");
    }

    /**
     * 获取当前登录用户的权限字符串
     *
     * @param request
     * @return
     */
    @RequestMapping({"/main/getStringPermissions"})
    @ResponseBody
    public Collection<String> getStringPermissions(HttpServletRequest request) {
        return myShiroRealm.getStringPermissions();
    }

    @RequestMapping("/main/unLock")
    @ResponseBody
    public Response unLock(String pwd) {
        pwd = Base64Utils.decode(pwd);
        String username = WebUtils.getLoginUserName();
        UserInfo userInfo = this.userInfoService.findByUsername(username);
        String credentialsPwd = encipherPwd.getCredentialsPwd(userInfo.getUsername(), pwd, userInfo.getSalt());
        if (credentialsPwd.equals(userInfo.getPassword())) {
            return new Response("0001", "解屏成功");
        } else {
            return new Response("9999", "密码错误");
        }
    }

    /**
     * 菜单管理界面
     *
     * @param request
     * @param model
     */
    @RequestMapping({"/main/menu"})
    public void menu(HttpServletRequest request, ModelMap model) {
        Object obj = SecurityUtils.getSubject().getPrincipal();
        Precondition.checkSqdsArguement(obj != null && !"".equals(obj.toString()), "未登录用户");

        String username = String.valueOf(obj);
        UserInfo userInfo = this.userInfoService.findByUsername(username);
        model.addAttribute("userInfo", userInfo);
    }

}
